package com.tgy.leetcode;

import java.util.PriorityQueue;
import java.util.Queue;

/**
 * @Author: tgy
 * @Date: 2021/2/21 下午10:31
 */
public class _1438_绝对差不超过限制的最长连续子数组 {

    public static int longestSubarray(int[] nums, int limit) {

        int left = 0, right = 0;
        int max_len = Integer.MIN_VALUE;
        Queue<Integer> minHeap = new PriorityQueue<>();
        Queue<Integer> maxHeap = new PriorityQueue<>((x1,x2)->{
            return x2 - x1;
        });
        minHeap.offer(nums[left]);
        maxHeap.offer(nums[left]);
        while (right < nums.length) {

            // 更新最大值和最小值
           if (maxHeap.peek() - minHeap.peek() > limit) {
               max_len = Math.max(max_len,right - left);
               maxHeap.remove(nums[left]);
               minHeap.remove(nums[left]);
               left++;
           }else {
               right++;
               if (right < nums.length) {

                   maxHeap.offer(nums[right]);
                   minHeap.offer(nums[right]);
               }
           }
        }

        max_len = Math.max(max_len,right - left);

        return max_len;
    }


    public static void main(String[] args) {

        int[] nums = {8,2,4,7};
        int k = 4;
        int result = longestSubarray(nums, k);
        System.out.println(result);

    }
}
